<template>
  <!-- 充电桩 详细信息 -->
  <div class="cardTitle">
    充电桩详细信息
    <a-icon type="link" class="linkIcon" />
  </div>
  <div class="chartContainer">
    <div class="chartItem">
      <div class="chartTitle">当月充电客户数</div>
      <div class="chartValue">
        {{ chargeGunCount }}<span class="unit">个</span>
      </div>
      <div ref="chargeGunChart" class="chart"></div>
    </div>
    <div class="chartItem">
      <div class="chartTitle">当月收入</div>
      <div class="chartValue">
        {{ monthlyIncome }}<span class="unit">元</span>
      </div>
      <div ref="incomeChart" class="chart"></div>
    </div>
    <div class="chartItem">
      <div class="chartTitle">当月充电量</div>
      <div class="chartValue">
        {{ monthlyCharge }}<span class="unit">kWh</span>
      </div>
      <div ref="chargeChart" class="chart"></div>
    </div>
    <div class="chartItem">
      <div class="chartTitle">当月服务次数</div>
      <div class="chartValue">
        {{ monthlyService }}<span class="unit">次</span>
      </div>
      <div ref="serviceChart" class="chart"></div>
    </div>
  </div>
</template>
<script setup>
import * as echarts from "echarts";
const props = defineProps({
  pileDetails: {
    type: Object,
    default: () => ({}),
  },
});
watch(
  () => props.pileDetails,
  async(newVal) => {
    if (newVal) {
      // 从 pileDetails 中提取月份数据
      const months = newVal.map(item => item.month || '');
      
      // 按月份提取四种数据
      lineData.value.chargeGun = newVal.map((item) => item.chargeCustomerNum);
      lineData.value.income = newVal.map((item) => item.totalFee);
      lineData.value.charge = newVal.map((item) => item.totalElectricity);
      lineData.value.service = newVal.map((item) => item.orderNum);
      
      // 获取各数组的最后一个值作为当月值
      const lastIndex = lineData.value.chargeGun.length - 1;
      chargeGunCount.value = lastIndex >= 0 ? (lineData.value.chargeGun[lastIndex] || 0) : 0;
      monthlyIncome.value = lastIndex >= 0 ? (lineData.value.income[lastIndex] || 0) : 0;
      monthlyCharge.value = lastIndex >= 0 ? (lineData.value.charge[lastIndex] || 0) : 0;
      monthlyService.value = lastIndex >= 0 ? (lineData.value.service[lastIndex] || 0) : 0;
      updateChartXAxis(months);
      await initChart();
    }
  }
);

// 更新图表 xAxis 数据的函数
const updateChartXAxis = (months) => {
  // 保存月份数据，供图表初始化时使用
  chartMonths.value = months;
  
  // 如果图表已经初始化，则更新它们的 xAxis 数据
  if (chargeGunChartInstance) {
    chargeGunChartInstance.setOption({
      xAxis: { data: months }
    });
  }
  
  if (incomeChartInstance) {
    incomeChartInstance.setOption({
      xAxis: { data: months }
    });
  }
  
  if (chargeChartInstance) {
    chargeChartInstance.setOption({
      xAxis: { data: months }
    });
  }
  
  if (serviceChartInstance) {
    serviceChartInstance.setOption({
      xAxis: { data: months }
    });
  }
};

// 添加月份数据引用
const chartMonths = ref([]);

// 图表DOM引用
const chargeGunChart = ref(null);
const incomeChart = ref(null);
const chargeChart = ref(null);
const serviceChart = ref(null);

// 图表实例
let chargeGunChartInstance = null;
let incomeChartInstance = null;
let chargeChartInstance = null;
let serviceChartInstance = null;

// 数据
const chargeGunCount = ref(0);
const monthlyIncome = ref(0);
const monthlyCharge = ref(0);
const monthlyService = ref(0);
const lineData = ref({
  chargeGun: [],
  income: [],
  charge: [],
  service: [],
});

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    // 确保DOM已渲染
    initChargeGunChart();
    initIncomeChart();
    initChargeChart();
    initServiceChart();
  });
};

// 充电枪趋势图
const initChargeGunChart = () => {
  if (chargeGunChartInstance) {
    chargeGunChartInstance.dispose();
  }
  chargeGunChartInstance = echarts.init(chargeGunChart.value);

  const option = {
    tooltip: {
      trigger: "axis",
      formatter: function(params) {
        const monthName = params[0].name || '';
        const value = params[0].value || 0;
        return `<div style="text-align:center;">
                  <div style="font-size:12px;color:#fff;padding-bottom:4px;border-bottom:1px solid rgba(255,255,255,0.2);margin-bottom:4px;">${monthName}</div>
                  <div style="font-size:14px;font-weight:bold;color:#ff626f;">${value}<span style="font-size:12px;font-weight:normal;margin-left:2px;">个</span></div>
                </div>`;
      },
      backgroundColor: "rgba(13, 20, 41, 0.8)",
      borderColor: "rgba(255, 98, 111, 0.3)",
      textStyle: {
        color: "#fff",
      },
      padding: [8, 12],
      extraCssText: 'border-radius: 4px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);'
    },
    grid: {
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
    },
    xAxis: {
      type: "category",
      data: chartMonths.value,
      show: false,
      boundaryGap: false,
    },
    yAxis: {
      type: "value",
      show: false,
    },
    series: [
      {
        data: lineData.value.chargeGun,
        // data: [10,60,30,15,50,60,70,100,20,10,64,71],
        type: "line",
        smooth: false,
        showSymbol: false,
        lineStyle: {
          width: 2,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [{
              offset: 0,
              color: '#d74177'
            }, {
              offset: 1,
              color: '#fe9f8a'
            }]
          }
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(255, 98, 111, 0.3)",
              },
              {
                offset: 1,
                color: "rgba(255, 98, 111, 0)",
              },
            ],
          },
        },
      },
    ],
    animation: false,
  };

  chargeGunChartInstance.setOption(option);
};

// 当月收入趋势图
const initIncomeChart = () => {
  if (incomeChartInstance) {
    incomeChartInstance.dispose();
  }
  incomeChartInstance = echarts.init(incomeChart.value);

  const option = {
    tooltip: {
      trigger: "axis",
      formatter: function(params) {
        const monthName = params[0].name || '';
        const value = params[0].value || 0;
        return `<div style="text-align:center;">
                  <div style="font-size:12px;color:rgba(255,255,255,0.7);padding-bottom:4px;border-bottom:1px solid rgba(255,255,255,0.2);margin-bottom:4px;">${monthName}</div>
                  <div style="font-size:14px;font-weight:bold;color:#61cca4;">${value}<span style="font-size:12px;font-weight:normal;margin-left:2px;">元</span></div>
                </div>`;
      },
      backgroundColor: "rgba(13, 20, 41, 0.8)",
      borderColor: "rgba(97, 204, 164, 0.3)",
      textStyle: {
        color: "#fff",
      },
      padding: [8, 12],
      extraCssText: 'border-radius: 4px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);'
    },
    grid: {
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
    },
    xAxis: {
      type: "category",
      data: chartMonths.value,
      show: false,
      boundaryGap: false,
    },
    yAxis: {
      type: "value",
      show: false,
    },
    series: [
      {
        data: lineData.value.income,
        // data: [10,60,30,15,50,60,70,100,20,10,64,71],
        type: "line",
        smooth: false,
        showSymbol: false,
        lineStyle: {
          width: 2,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [{
              offset: 0,
              color: '#22e3ab'
            }, {
              offset: 1,
              color: '#0aafe8'
            }]
          }
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(97, 204, 164, 0.3)",
              },
              {
                offset: 1,
                color: "rgba(97, 204, 164, 0)",
              },
            ],
          },
        },
      },
    ],
    animation: false,
  };

  incomeChartInstance.setOption(option);
};

// 当月充电量图表
const initChargeChart = () => {
  if (chargeChartInstance) {
    chargeChartInstance.dispose();
  }
  chargeChartInstance = echarts.init(chargeChart.value);

  const option = {
    tooltip: {
      trigger: "axis",
      formatter: function(params) {
        const monthName = params[0].name || '';
        const value = params[0].value || 0;
        return `<div style="text-align:center;">
                  <div style="font-size:12px;color:rgba(255,255,255,0.7);padding-bottom:4px;border-bottom:1px solid rgba(255,255,255,0.2);margin-bottom:4px;">${monthName}</div>
                  <div style="font-size:14px;font-weight:bold;color:#8fda6e;">${value}<span style="font-size:12px;font-weight:normal;margin-left:2px;">kWh</span></div>
                </div>`;
      },
      backgroundColor: "rgba(13, 20, 41, 0.8)",
      borderColor: "rgba(143, 218, 110, 0.3)",
      textStyle: {
        color: "#fff",
      },
      padding: [8, 12],
      extraCssText: 'border-radius: 4px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);'
    },
    grid: {
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
    },
    xAxis: {
      type: "category",
      data: chartMonths.value,
      show: false,
    },
    yAxis: {
      type: "value",
      show: false,
    },
    series: [
      {
        data: lineData.value.charge,
        type: "bar",
        barWidth: 4,
        itemStyle: {
          color: "#8fda6e",
          borderRadius: [8, 8, 8, 8],
        },
      },
    ],
    animation: false,
  };

  chargeChartInstance.setOption(option);
};

// 当月服务次数图表
const initServiceChart = () => {
  if (serviceChartInstance) {
    serviceChartInstance.dispose();
  }
  serviceChartInstance = echarts.init(serviceChart.value);

  const option = {
    tooltip: {
      trigger: "axis",
      formatter: function(params) {
        const monthName = params[0].name || '';
        const value = params[0].value || 0;
        return `<div style="text-align:center;">
                  <div style="font-size:12px;color:rgba(255,255,255,0.7);padding-bottom:4px;border-bottom:1px solid rgba(255,255,255,0.2);margin-bottom:4px;">${monthName}</div>
                  <div style="font-size:14px;font-weight:bold;color:#f9c967;">${value}<span style="font-size:12px;font-weight:normal;margin-left:2px;">次</span></div>
                </div>`;
      },
      backgroundColor: "rgba(13, 20, 41, 0.8)",
      borderColor: "rgba(249, 201, 103, 0.3)",
      textStyle: {
        color: "#fff",
      },
      padding: [8, 12],
      extraCssText: 'border-radius: 4px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);'
    },
    grid: {
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
    },
    xAxis: {
      type: "category",
      data: chartMonths.value,
      show: false,
    },
    yAxis: {
      type: "value",
      show: false,
    },
    series: [
      {
        data: lineData.value.service,
        type: "bar",
        barWidth: 4,
        itemStyle: {
          color: "#f9c967",
          borderRadius: [8, 8, 8, 8],
        },
      },
    ],
    animation: false,
  };

  serviceChartInstance.setOption(option);
};

// 页面初始化
const initChart = async () => {
  // 初始化图表
  nextTick(() => {
    initCharts();
  });
};

// 处理窗口大小变化
const handleResize = () => {
  chargeGunChartInstance && chargeGunChartInstance.resize();
  incomeChartInstance && incomeChartInstance.resize();
  chargeChartInstance && chargeChartInstance.resize();
  serviceChartInstance && serviceChartInstance.resize();
};

onMounted(async () => {
  window.addEventListener("resize", handleResize);
});

// 组件卸载时清理
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
  chargeGunChartInstance && chargeGunChartInstance.dispose();
  incomeChartInstance && incomeChartInstance.dispose();
  chargeChartInstance && chargeChartInstance.dispose();
  serviceChartInstance && serviceChartInstance.dispose();
});
</script>
<style scoped lang="less">
.chartContainer {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  gap: 20px;
}

.cardTitle {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #fff;
  border-left: 4px solid #4e83fd;
  padding-left: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .linkIcon {
    font-size: 14px;
    color: #4e83fd;
    cursor: pointer;
  }
}

.chartItem {
  width: calc(50% - 10px);
  height: 140px;
  padding: 12px;
  position: relative;
  overflow: hidden;
}

.chartTitle {
  font-size: 15px;
  color: #739dc2;
  margin-bottom: 10px;
}

.chartValue {
  font-size: 22px;
  font-weight: bold;
  color: #66bbf9;

  .unit {
    font-size: 18px;
    margin-left: 5px;
    font-weight: normal;
    opacity: 0.8;
  }
}

.chart {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 60px;
}
</style>
